//
//  FindViewController.m
//  ChengXinBao
//
//  Created by RongZhou on 17/2/13.
//  Copyright © 2017年 RongZhou. All rights reserved.
//

#import "FindViewController.h"
#import "JJSearchProvinceTableController.h"
#import "CompanyInfoModel.h"
#import "CompanyInforCell.h"
#import "CompanyDetailViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <AFNetworking.h>
#import <MJRefresh.h>
@interface FindViewController ()<CLLocationManagerDelegate,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchControllerDelegate>
{
//    //定位管理器
//    CLLocationManager *_locationManager;
    int _startPage;
    int _endPage;
}

@property (nonatomic,strong)UIButton *letfButton;

@property (nonatomic,strong)UIButton *rightButton;

@property(nonatomic,copy)NSString *localCity;
@property(nonatomic,copy)NSString *cityCode;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)UISearchBar *searchBar;
@property(nonatomic,assign)BOOL isSearch;
@property(nonatomic,strong)NSMutableArray *matchDataArray;
@property(nonatomic,strong)AFHTTPSessionManager *manager;
@property(nonatomic,copy)NSString *searchtext;
@end

@implementation FindViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self.navigationController.navigationBar setBarTintColor:[UIColor redColor]];
    
    // 设置导航栏左侧按钮
    self.letfButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.letfButton.backgroundColor = [UIColor blueColor];
    self.letfButton.layer.cornerRadius = 10;
    self.letfButton.layer.masksToBounds = YES;
    self.letfButton.frame = CGRectMake(-50, 0, 100,20);
//    [self.letfButton setTitleColor:[UIColor cyanColor] forState:UIControlStateNormal];
    self.letfButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.letfButton setTitle:@"全国" forState:UIControlStateNormal];
    [self.letfButton setImage:[UIImage imageNamed:@"zhankai"] forState:UIControlStateNormal];
    [self.letfButton addTarget:self action:@selector(gotoProvincePage) forControlEvents:UIControlEventTouchUpInside];
    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backCityName:) name:@"cityName" object:nil];
    
    UIBarButtonItem *LeftBarButton = [[UIBarButtonItem alloc] initWithCustomView:self.letfButton];
    self.navigationItem.leftBarButtonItem = LeftBarButton;
//    self.automaticallyAdjustsScrollViewInsets = NO;
    // 设置导航栏右侧按钮
//    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.rightButton.frame = CGRectMake(0, 0, 22, 21);
//    self.rightButton.userInteractionEnabled = NO;
//    [self.rightButton addTarget:self action:@selector(louDouAction:) forControlEvents:UIControlEventTouchUpInside];
//    //    [self.rightButton setBackgroundImage:[UIImage imageNamed:@"shaixuan"] forState:UIControlStateNormal];
//    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
//    self.navigationItem.rightBarButtonItem = rightBarButton;
    //设置搜索框
    _searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(70,20,ScreenWidth - 140,40)];
    _searchBar.delegate=self;
    _searchBar.backgroundColor=[UIColor clearColor];
    _searchBar.placeholder=@"请输入商家信息";
//    _searchBar.searchBarStyle=UISearchBarStyleMinimal;
    self.navigationItem.titleView = _searchBar;
    [self initUIAboutTableView:0];
    [self addRefresh];
    [self.tableView.mj_header beginRefreshing];
}
-(void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
}
-(void)initUIAboutTableView:(NSInteger)integ{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, integ, ScreenWidth, ScreenHeight - integ) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    UINib *nib = [UINib nibWithNibName:@"CompanyInforCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"CompanyInforCell"];
}


-(void)gotoProvincePage{
    [self.navigationController pushViewController:[JJSearchProvinceTableController new] animated:YES];
}
#pragma mark -tableview的代理方法
/*******************************监听到通知执行的方法*********************************/
- (void)backCityName:(NSNotification *)noti {
    NSLog(@"---%@",noti.userInfo[@"cityName"]);
    // 在此处给选择城市的button设置文字
    [self.letfButton setTitle:noti.userInfo[@"cityName"] forState:UIControlStateNormal];
    self.cityCode = noti.userInfo[@"cityCode"];
    [self addRefresh];
    [self.tableView.mj_header beginRefreshing];
    
}
/**
 *  添加刷新的方法
 */
-(void)addRefresh{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshNewData)];
    self.tableView.mj_footer = [MJRefreshBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];

}
//下拉刷新执行的方法，只执行最新的方法
-(void)refreshNewData{
    _startPage = 0;
    _endPage = 20;
    [self getCompanyInforWithStartPage:_startPage andEndPage:_endPage];
}
-(void)loadMoreData{
    _startPage = _endPage;
    _endPage += 20;
    [self getCompanyInforWithStartPage:_startPage andEndPage:_endPage];
}

/**
 *  获取到请求的数据
 *
 *  @param startPage
 *  @param endPage
 */
-(void)getCompanyInforWithStartPage:(int) startPage andEndPage:(int) endPage{
    _manager = [AFHTTPSessionManager manager];
    _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    if (self.cityCode == nil) {
        NSString *str = ServiceUrl@"/customerApp/searchCustomerList?start=%d&end=%d";
        NSString *url = [NSString stringWithFormat:str,startPage,endPage];
        NSLog(@"%@",url);
        [_manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSArray *array = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSMutableArray *array1 = [[NSMutableArray alloc] init];
            for (NSDictionary *dict in array) {
                CompanyInfoModel *model = [[CompanyInfoModel alloc] initWithBackDictionry:dict];
                [array1 addObject:model];
            }
            if (endPage == 20) {
                [self.dataArray removeAllObjects];
            }
            [self.dataArray addObjectsFromArray:array1];
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            NSLog(@"%@",array);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
        }];

    }else{
        NSLog(@"%@",self.cityCode);
        NSString *str = ServiceUrl@"/customerApp/searchCustomerListByCityCode?cityCode=%@&start=%d&end=%d";
        NSString *url = [NSString stringWithFormat:str,self.cityCode,startPage,endPage];
        [_manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSArray *array = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSMutableArray *array1 = [[NSMutableArray alloc] init];
            for (NSDictionary *dict in array) {
                CompanyInfoModel *model = [[CompanyInfoModel alloc] initWithBackDictionry:dict];
                [array1 addObject:model];
            }
            if (endPage == 20) {
                [self.dataArray removeAllObjects];
            }
            [self.dataArray addObjectsFromArray:array1];
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            NSLog(@"%@",array);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
        }];

    }
}
#pragma mark -tableview的代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CompanyInforCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"CompanyInforCell"];
    cell.model = self.dataArray[indexPath.row];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CompanyInfoModel *model = self.dataArray[indexPath.row];
    CompanyDetailViewController *vc = [[CompanyDetailViewController alloc] init];
    vc.companyaddress = model.customerAddr;
    vc.companyname = model.customerName;
    vc.companyphone = model.phoneNumber;
    vc.companyid = model.customerId;
    vc.companylogo = model.logo;
    vc.companyCityname = model.cityName;
    vc.companyAreaname = model.areaName;
    vc.companyWebid = model.companyId;
    vc.companyIntroduce = model.introduce;
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
/**
 *  添加搜索元数据搜索
 *
 *  @param searchText <#searchText description#>
 */
-(void)addsearchDataRefresh:(NSString *)searchText{
    self.searchtext = searchText;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshNewSeachData)];
    self.tableView.mj_footer = [MJRefreshBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreSearchData)];

}
//下拉刷新执行的方法，只执行最新的方法
-(void)refreshNewSeachData{
    _startPage = 0;
    _endPage = 20;
    [self getSearchResultDataWithStartpage:_startPage AndEndPage:_endPage AndUseSearchtext:self.searchtext];
}
-(void)loadMoreSearchData{
    _startPage = _endPage;
    _endPage += 20;
    [self getSearchResultDataWithStartpage:_startPage AndEndPage:_endPage AndUseSearchtext:self.searchtext];
}

/**
 *  获取到搜索的数据
 *
 *
 */
-(void)getSearchResultDataWithStartpage:(int) startPage AndEndPage:(int) endPage AndUseSearchtext:(NSString *)searchText{
    _manager = [AFHTTPSessionManager manager];
    _manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    if (self.cityCode == nil) {
        NSString *str = ServiceUrl@"/customerApp/searchCustomer?nameOrPhone=%@&cityCode=no&start=%d&end=%d";
        NSString *url = [NSString stringWithFormat:str,searchText,startPage,endPage];
        NSLog(@"我是搜索的字符串啊%@",url);
        [_manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSArray *array = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSMutableArray *array1 = [[NSMutableArray alloc] init];
            for (NSDictionary *dict in array) {
                CompanyInfoModel *model = [[CompanyInfoModel alloc] initWithBackDictionry:dict];
                [array1 addObject:model];
            }
            if (endPage == 20) {
                [self.dataArray removeAllObjects];
            }
            [self.dataArray addObjectsFromArray:array1];
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            NSLog(@"%@",array);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
        }];
        
    }else{
        NSLog(@"%@",self.cityCode);
        NSString *str = ServiceUrl@"/customerApp/searchCustomer?nameOrPhone=%@&cityCode=%@&start=%d&end=%d";
        NSString *url = [NSString stringWithFormat:str,searchText,self.cityCode,startPage,endPage];
        [_manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSArray *array = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSMutableArray *array1 = [[NSMutableArray alloc] init];
            for (NSDictionary *dict in array) {
                CompanyInfoModel *model = [[CompanyInfoModel alloc] initWithBackDictionry:dict];
                [array1 addObject:model];
            }
            if (endPage == 20) {
                [self.dataArray removeAllObjects];
            }
            [self.dataArray addObjectsFromArray:array1];
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            NSLog(@"%@",array);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
        }];
        
    }
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    [self.dataArray removeAllObjects];
    if (searchText.length <= 0) {
        _isSearch = NO;
        [self initUIAboutTableView:64];
        [self addRefresh];
        [self.tableView.mj_header beginRefreshing];
    }else{
        _isSearch = YES;
        NSString *str = [searchText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [self initUIAboutTableView:64];
        [self addsearchDataRefresh:str];
        [self.tableView.mj_header beginRefreshing];
    }
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    _searchBar.showsCancelButton = NO;
    [_searchBar resignFirstResponder];
    _searchBar.text = @"";
    _isSearch = NO;
    [self addRefresh];
    [self.tableView.mj_header beginRefreshing];
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    _searchBar.showsCancelButton = YES;
}
/*
#pragma mark - 地图定位的代理方法
-(void)initCLlocation{
    //初始化
    _locationManager = [[CLLocationManager alloc]init];
    //iOS8以后，请求定位的时候，需要在info.plist文件里面加入一个字段
    //    NSLocationAlwaysUsageDescription（一直定位，后台的也能定位）
    //    NSLocationWhenInUseUsageDescription（使用的时候定位）
    //在iOS8以后，请求定位需要调用下面的方法
    //做版本判断是因低版本调用高版本的方法，会出现崩溃
    if ([[[UIDevice currentDevice]systemVersion]floatValue]>= 8.0) {
        [_locationManager requestWhenInUseAuthorization];
        [_locationManager requestAlwaysAuthorization];
    }
    //设置定位的距离
    //用户移动50米，会调用一次代理
    _locationManager.distanceFilter = 50;
    //设置精确度，精确度越高，越费电
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //设置代理
    _locationManager.delegate = self;

}
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    if (status == kCLAuthorizationStatusNotDetermined) {
        NSLog(@"等待用户授权");
    }else if (status ==kCLAuthorizationStatusAuthorizedAlways||status ==kCLAuthorizationStatusAuthorizedWhenInUse){
        NSLog(@"授权成功");
        //开始定位
        [_locationManager startUpdatingLocation];
    }else{
        NSLog(@"失败");
    }

}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    //拿到用户最新的位置信息
    CLLocation *currentLocation = [locations lastObject];
    NSLog(@"经度 %lf--纬度%lf",currentLocation.coordinate.longitude,currentLocation.coordinate.latitude);
    
    [self reverseCode:currentLocation];

}
//定位失败
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"定位失败%@",error);
}
-(void)reverseCode:(CLLocation *)location{
    //编码对象
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //进行反向地理编码
    [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        // CLPlacemark  详细的地址信息
        if (placemarks.count == 0) {
            NSLog(@"反向地理编码失败");
            return ;
        }
        CLPlacemark *placeMark = [placemarks lastObject];
        //        NSLog(@"placeMark = %@",placeMark);
        NSLog(@"placeMark = %@",placeMark.addressDictionary);
        NSArray *keys = [placeMark.addressDictionary allKeys];
        NSLog(@"我是城市%@",placeMark.addressDictionary[@"SubLocality"]);
        NSString *cityStr = (NSString *)placeMark.addressDictionary[@"City"];
        [[NSUserDefaults standardUserDefaults] setObject:cityStr forKey:@"localCity"];
        [self.letfButton setTitle:cityStr forState:UIControlStateNormal];
        for (NSString *key in keys) {
            NSLog(@"%@",[placeMark.addressDictionary objectForKey:key]);
        }
        
    }];
}


- (void)louDouAction:(UIButton *)sender{
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

*/
@end
